package com.fadadianqi.logistics.admin.printer;

import com.yeqiangwei.commons.util.StringHelper;
import com.yeqiangwei.commons.util.TypeChange;
import org.apache.log4j.Logger;

import java.awt.*;
import java.awt.print.*;

public class LocalPrinter implements Printable {


    private static final Logger log = Logger.getLogger(LocalPrinter.class);

    private int fontSize = 9;
    private static final String FONT_NAME = "宋体";

    private String content = null; // 打印内容

    public LocalPrinter(String content) {
        this.content = content;
    }

    @Override
    public int print(Graphics g, PageFormat pf, int page)
            throws java.awt.print.PrinterException {
        if (page > 0) {
            return NO_SUCH_PAGE;
        }
        Graphics2D g2d = (Graphics2D) g;
        g2d.translate(pf.getImageableX(), pf.getImageableY());
        String[] linesText = content.split("\n");
        int x = 0, y = 0, size = fontSize;
        for (String text : linesText) {
            text = text.trim();
            if (text.length() <= 0) {
                g2d.drawString(" ", 0, y + size);
                continue;
            }
            // 字体尺寸
            String _size = StringHelper.getReplacement(text.trim(), "\\[fz=(.*?)\\](.*?)\\[\\/fz\\]", "$1", null);
            size = TypeChange.stringToInt(_size, size); // 当前行文字尺寸
            text = StringHelper.getReplacement(text, "\\[fz=(.*?)\\](.*?)\\[\\/fz\\]", "$2", text);

            // 获得打印x坐标
            String _x = StringHelper.getReplacement(text, "\\[x=(.*?)\\](.*?)\\[\\/x\\]", "$1", null);
            x = TypeChange.stringToInt(_x, x);
            text = StringHelper.getReplacement(text, "\\[x=(.*?)\\](.*?)\\[\\/x\\]", "$2", text);

            // 获得打印y坐标
            String _y = StringHelper.getReplacement(text, "\\[y=(.*?)\\](.*?)\\[\\/y\\]", "$1", null);
            y = TypeChange.stringToInt(_y, y + size);  // 如果y坐标获取不到则默认按照前次行高增加一行
            text = StringHelper.getReplacement(text, "\\[y=(.*?)\\](.*?)\\[\\/y\\]", "$2", text);

            Font _font = new Font(FONT_NAME, Font.PLAIN, size);
            g2d.setFont(_font);

            //text = text.replaceAll("\\[(.*?)\\]", StringHelper.EMPTY);
            log.debug("_fz=" + _size + ", _x=" + _x + ", _y=" + _y);
            log.debug("fz=" + size + ", x=" + x + ", y=" + y);
            log.debug("text=" + text);

            g2d.drawString(formatText(text), x, y);
        }
        return PAGE_EXISTS;
    }

    public String formatText(String text) {
        return text;
    }
}
